# Virtual Router Simulator 
#
# Copyright (C) 2009-2010 VRSim Project
# Author: Choonho Son <choonho@kt.com>
# URL: <http://vrsim.googlecode.com>
# For license information, see LICENSE.TXT
#

import VRSim.Globals as globals

from PyQt4 import QtSvg,  QtCore,  QtGui
from VRSim.Utils import debug,  message

class GUIInfo(QtSvg.QGraphicsSvgItem):
    def __init__(self, normal_img,  selected_img):
        QtSvg.QGraphicsSvgItem.__init__(self)
        
        self.nodeid = None
        self.hostname = None
        self.__flag_hostname = False
        
        # Icon Dic
        self.__render_normal = normal_img
        self.__render_select = selected_img
        self.__edgeList = set()
        
        self.setFlags(self.ItemIsMovable | self.ItemIsSelectable | self.ItemIsFocusable)
        self.setAcceptsHoverEvents(True)
        self.setZValue(1)
        self.setSharedRenderer(self.__render_normal)
        
        self.hostname_xpos = None
        self.hostname_ypos = None
        
        self.default_hostname_xpos = None
        self.default_hostname_ypos = None
        
    def paint(self,  painter,  option,  widget =None):
        _local_option = option
        
        QtSvg.QGraphicsSvgItem.paint(self,  painter,  _local_option,  widget)
    
    def getEdgeList(self):
        # return edges
        return self.__edgeList
    
    # update side effect
    # GUI: nodesSummary
    # AP : 
    def updateSideEffect(self):
        globals.GApp.mainWindow.NodesSummary.refresh()
        
    ##############################
    # About Hostname
    ##############################

    def showHostname(self):
        if self.__flag_hostname == True:
            return
        
        hostname = self.hostname
        if type(hostname) != unicode:
            hostname = unicode(hostname)
        self.textItem = QtGui.QGraphicsTextItem(hostname,  self)
        self.textItem.setFont(QtGui.QFont("TypeWriter",  10,  QtGui.QFont.Bold))
        self.textItem.setFlag(self.textItem.ItemIsMovable)
        self.textItem.setZValue(2)
        if self.hostname_xpos == None and self.hostname_ypos == None:
            # use default positions
            if self.default_hostname_xpos == None and self.default_hostname_ypos == None:
                # compute default positions once
                textrect = self.textItem.boundingRect()
                textmiddle = textrect.topRight() / 2
                noderect = self.boundingRect()
                nodemiddle = noderect.topRight() / 2
                self.default_hostname_xpos = nodemiddle.x() - textmiddle.x() 
                self.default_hostname_ypos = -15 # -25
            self.textItem.setPos(self.default_hostname_xpos, self.default_hostname_ypos)
        else:
            # use user defined positions
            self.textItem.setPos(self.hostname_xpos, self.hostname_ypos)
        self.__flag_hostname = True
     
    def updateHostname(self,  name):
        print "updateHostname: " , name
        self.hostname = name
        if self.__flag_hostname:
            self.removeHostname()
            self.showHostname()
        
        # update Summary
        self.updateSideEffect()
            
    def changeHostname(self):
        """ Called when slotChHostname in TopologyDesigner
        """
        # if node is running, cant change hostname
        node = globals.GApp.topology.getNode(self.nodeid)
        nodestate = node.physnode.state
        if nodestate == globals.START:
            msg = "Can not change Hostname, when node is running"
            message(msg, "critical")
            return False
            
        msg = "Hostname (" + self.hostname + ") : "
        (text,  ok) = QtGui.QInputDialog.getText(globals.GApp.mainWindow,  "Chnage Hostname",  msg,  QtGui.QLineEdit.Normal,  self.hostname)
        
        if ok and text:
            text = unicode(text).replace(' ', '')
            text = text.replace(':', ',')
            for node in globals.GApp.topology.nodes.itervalues():
                if text == node.physnode.hostname:
                    QtGui.QMessageBox.critical(globals.GApp.mainWindow,  "Hostname",  "Hostname already used")
                    return
            # change hostname (guiinfo, physnode)
            self.hostname = text
            node = globals.GApp.topology.nodes[self.nodeid]
            node.physnode.hostname = text
        
        if self.__flag_hostname:
            self.removeHostname()
            self.showHostname()
        
        # update Summary
        self.updateSideEffect()
         
    # No Direct call from GUI 
    def removeHostname(self):
        """ removeHostname from topology
        """
        if self.__flag_hostname == True:
            if self.textItem.x() != self.default_hostname_xpos or self.textItem.y() != self.default_hostname_ypos:
                self.hostname_xpos = self.textItem.x()
                self.hostname_ypos = self.textItem.y()
            globals.GApp.topology.removeItem(self.textItem)
            self.__flag_hostname = False
        
    #################
    # Edges
    #################
    def itemChange(self,  change,  value):
        if self.isSelected() == True:
            self.setSharedRenderer(self.__render_select)
        else:
            self.setSharedRenderer(self.__render_normal)
            
        if change == self.ItemPositionChange or change == self.ItemPositionHasChanged:
            for edge in self.__edgeList:
                edge.adjust()
                
        return QtGui.QGraphicsItem.itemChange(self,  change,  value)
        
        
    def addEdge(self,  edge):
        self.__edgeList.add(edge)
        edge.adjust()
        
    def deleteEdge(self,  edge):
        """ Delete edge
        """
        if edge in self.__edgeList:
            self.__edgeList.remove(edge)
        
    def smart_interface(self,  link_type):
        connected_interfaces = self.getConnectedInterfaceList()
        
    #########################
    # Events
    #########################
    def hoverEnterEvent(self,  event):
        if not self.isSelected() and self.__render_normal:
            self.setSharedRenderer(self.__render_select)
        
    def hoverLeaveEvent(self,  event):
        if not self.isSelected() and self.__render_select:
            self.setSharedRenderer(self.__render_normal)
            
    def mousePressEvent(self,  event):
        if globals.addingLinkFlag and event.button() == QtCore.Qt.LeftButton:
            self.__selectedInterface = None
            self.emit(QtCore.SIGNAL("Add link"),  self.nodeid,  self.__selectedInterface)
        
        QtSvg.QGraphicsSvgItem.mousePressEvent(self,  event)
       
    def mouseReleaseEvent(self,  event):
        # default event
        print "dragLeaveEvent"
        QtSvg.QGraphicsSvgItem.mouseReleaseEvent(self,  event)
        # update location information
        pnode = globals.GApp.topology.nodes[self.nodeid].physnode
        x = self.x()
        y = self.y()
        pnode.setPos(x, y)
        print x,  y
        
